<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';

import { onMounted, ref } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

import { CalendarOutlined } from '@ant-design/icons-vue';
import { RangePicker } from 'ant-design-vue';
import dayjs from 'dayjs';

import { onlineStatistics } from '#/api/dashboard/analysis';

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
const time = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
  dayjs().subtract(6, 'day'),
  dayjs(),
]);

async function getData() {
  const data = await onlineStatistics({
    startDate: time.value[0].format('YYYY-MM-DD'),
    endDate: time.value[1].format('YYYY-MM-DD'),
  });

  await initEcharts(data);
}
function initEcharts(data: any[]) {
  renderEcharts({
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      top: '2%',
      left: '3%',
      right: '4%',
      bottom: '0',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.map(
        (item: {
          dateX: Date | dayjs.Dayjs | null | number | string | undefined;
        }) => dayjs(item.dateX).format('MM-DD'),
      ),
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '在线设备数',
        data: data.map((item: { countY: string }) => item.countY),
        type: 'line',
        lineStyle: {
          color: '#FF994D', // 这里可以设置线的颜色
        },
        itemStyle: {
          color: '#FF994D', // 设置数据点的颜色
        },
      },
    ],
  });
}

onMounted(() => {
  getData();
});
</script>

<template>
  <RangePicker
    v-model:value="time"
    :allow-clear="false"
    @change="getData"
    class="absolute right-4 top-5"
  >
    <template #default>
      <CalendarOutlined />
    </template>
  </RangePicker>
  <EchartsUI ref="chartRef" />
</template>
